package com.lanou.controller;

import com.lanou.bean.LayUIGridResultInfo;
import com.lanou.bean.ResponseInfo;
import com.lanou.bean.User;
import com.lanou.mapper.RoleMapper;
import com.lanou.mapper.UserMapper;
import com.lanou.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/user")
public class UserController {
    private ResponseInfo ret = new ResponseInfo();
    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @RequestMapping("/queryAdmins")
    @ResponseBody
    public LayUIGridResultInfo<User> queryAdmins(@RequestParam(value = "page", required = false, defaultValue = "1") Integer currentPage,
                                                 @RequestParam(value = "limit", required = false, defaultValue = "20") Integer pageSize){
        return userService.queryAdminsForLayUI(pageSize, currentPage);
    }


    @RequestMapping("/delete")
    public Integer deleteUserByID(Model model,@RequestParam("id")Integer id){
        int row=userService.update(id);
        ret.setCode(200);
        ret.setMessage("删除成功");

        return row;
    }
    @RequestMapping("/addUser")
    @ResponseBody
    public int addUser(String userName,String password, String phoneNumber,String email, String roleName){
        int i = userService.addUser(userName, password, phoneNumber, email, roleName);
        if (i == 1){
            return i;
        }
        return 0;
    }

    @RequestMapping("/modUser")
    public String modUser(Model model, @RequestParam Integer id)  {
        User user = userMapper.selectByPrimaryKey(id);
//        List<Role> roles = roleMapper.selectByExample(null);

        System.out.println(user);
//        model.addAttribute("roles",roles);
        model.addAttribute("id",user.getuId());
        model.addAttribute("userName",user.getuName());
        model.addAttribute("password",user.getuPassword());
        model.addAttribute("phoneNumber",user.getuTell());
        model.addAttribute("roleName",user.getuRole());
        model.addAttribute("email",user.getuMailbox());
        return "admin/admin-edit";
    }

    @ResponseBody
    @RequestMapping("/update")
    public ModelAndView updateUserInfo(ModelAndView mv, Integer uId, String uName, Integer uTell, String uMailbox, String uPassword){

        User user = new User( uId,  uName,  uPassword, uTell,  uMailbox);

        userMapper.updateUserByUser(user);

        mv.setViewName("admin/error");
        return mv;
    }
}
